package com.wenbing.miio.util;

import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class BytesUtils {

    /**
     * int 转 byte[]
     * @param number
     * @return
     */
    public static byte[] int2Bytes(int number) {
        return new byte[]{
                (byte) ((number >> 24) & 0xff),
                (byte) ((number >> 16) & 0xff),
                (byte) ((number >> 8) & 0xff),
                (byte) (number & 0xff)};
    }

    /**
     * 计算校验和
     * @param bs
     * @return
     */
    public static byte checksum(byte[] bs) {
        int checksum = 0;
        for (int i = 0; i < bs.length; i ++) {
            checksum += bs[i];
        }
        return (byte) checksum;
    }

    /**
     * 合并数组
     * @param bs
     * @return
     */
    public static byte[] marginArray(byte[]... bs){
        int length = Arrays.stream(bs)
                .mapToInt(Array::getLength)
                .sum();
        byte[] result = new byte[length];
        int index = 0;
        for (int i = 0 , l = bs.length ; i < l ; i ++){
            System.arraycopy(bs[i], 0, result, index, bs[i].length);
            index += bs[i].length;
        }
        return result;
    }

    /**
     * 重复数组
     * @param b
     * @param length
     * @return
     */
    public static byte[] repeat(byte b, int length){
        byte[] bs = new byte[length];
        Arrays.fill(bs, b);
        return bs;
    }

    /**
     * 16进制串转byte[]
     * @param hex
     * @return
     */
    public static byte[] hex2Bytes(String hex){
        // 奇数填0
        hex = ((hex.length()&0x01) == 1 ? "0" : "") + hex;
        int length = hex.length() / 2;
        byte[] bs = new byte[length];
        for (int i = 0; i < length ; i ++){
            int index = i << 1;         // i*2
            String item = hex.substring(index, index + 2);
            bs[i] = (byte) Integer.parseInt( item,16);
        }
        return bs;
    }

    private static final char[] dict = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * byte[]转16进制串
     * @param bytes
     * @return
     */
    public static String bytes2Hex(byte[] bytes){
        return bytes2Hex(bytes, 0, bytes.length);
    }

    /**
     * byte[]转16进制串
     * @param bytes
     * @param offset
     * @param length
     * @return
     */
    public static String bytes2Hex(byte[] bytes, int offset, int length){
        length = Math.min(length, bytes.length - offset);
        StringBuffer hex = new StringBuffer();
        for (int i = offset; i < length ; i ++){
            hex.append(dict[(bytes[i] >>> 4) & 0x0f]);
            hex.append(dict[bytes[i] & 0x0f]);
        }
        return hex.toString();
    }

    /**
     * byteBuffer转16进制串
     * @param byteBuffer
     * @return
     */
    public static String bytes2Hex(ByteBuffer byteBuffer) {
        return bytes2Hex(byteBuffer.array(), byteBuffer.arrayOffset(), byteBuffer.limit());
    }
}
